package com.hsh.controller;

import com.hsh.bean.Message;
import com.hsh.bean.User;
import com.hsh.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("/list")
    public String list() {
        return "/user/list";
    }

    @RequestMapping("/toUpdate/{uid}")
    public String toUpdate(@PathVariable Integer uid, Model model){
        User user = userService.findById(uid);
        model.addAttribute("user", user);
        return "/user/update";
    }

    @RequestMapping("/update")
    public String update(User user, Model model){
        Integer update = userService.update(user);
        Message msg = new Message();
        msg.setState(update - 1);
        msg.setResult(update == 1 ?"修改成功":"修改失败");
        model.addAttribute("updateState", msg);
        return "redirect:/user/info?uid="+user.getUid();
    }

    @RequestMapping("/toAdd")
    public String toAdd(){
        return "/user/add";
    }

    @RequestMapping("/add")
    public String add(User user){
        Integer add = userService.add(user);
//        Message msg = new Message();
//        msg.setState(add - 1);
//        msg.setResult(add == 0 ?"修成失败":"修改改功");
        return "redirect:/user/list";
    }

    @RequestMapping("/plan")
    public String plan(Integer uid, Model model){
        User user = userService.findById(uid);
        model.addAttribute("user", user);
        return "/user/plan";
    }

    @RequestMapping("info")
    public String info(Integer uid, Model model){
        User user = userService.findById(uid);
        model.addAttribute("user", user);
        return "/user/info";
    }

    @RequestMapping("/login")
    public String login(User user, Model model){
        List<User> loginUser = userService.login(user);
        if (loginUser.size() > 0) {
            System.out.println("userController"+loginUser.get(0));
            model.addAttribute("user", loginUser.get(0));
            return "/sleep/list";
//            return "redirect:/sleep/list";
        }
        return "/user/login";
    }
}
